import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, ScrollView, FlatList, BackHandler, Alert, Platform, TextInput, Dimensions, Animated
} from "react-native";
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { CURRENCY } from '../../../utils/helper';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { OrderCommon } from '../../order-new/_common/common';
import WarningService from '../_common/service';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import MethodUtil from '../../../utils/MethodUtil';


const scale = GLOBAL.SCALE;
const goBackEmpty = require('../../../imgs/goBackEmpty.png');
const showImg = require('../../../imgs/order/show.png');
const closeImg = require('../../../imgs/order/close.png');
export class SalesUncollected extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '销售未收款',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={goBackEmpty} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			refreshIcon: false,
			listData: []
		}

		this.reload = false;
		this.totalPage = 1;
		this.pageParams = {
			pageNo: 1,
			pageSize: 10,
			warnType: 'saleUncollected'
		};
	}

	componentWillMount() {
		this.initPage()
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let res = await WarningService.getWarnList(this.pageParams, { rejectError: true });
		if (res) {
			if (res.isReject) {
				this.setState({
					status: 'error',
					errorText: res.msg,
					refreshIcon: false
				})
			} else {
				this.totalPage = res.totalPage;
				res = this.getRequireParams(res);
				this.setState({
					status: res.rows.length > 0 ? 'data' : 'empty',
					listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
					refreshIcon: false
				})
			}
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 返回值数据补充
	getRequireParams = (res) => {
		if (res.rows && res.rows.length > 0) {
			res.rows.forEach(item => {
				item.showItem = false;
				item.boxHeight = new Animated.Value(138 * scale);
				item.openHeight = 0;
				// if (this.isZXY) item.orderItemList = item.zxyOrderItemList;
				if (item.orderItemList && item.orderItemList.length > 0) {
					item.openHeight = 69 * item.orderItemList.length
				} else {
					item.orderItemList = []
				}
			})
		}
		return res
	}

	// 重新加载
	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh = () => {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 加载更多
	loadMore = () => {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	// 刷新
	onErrorRefresh = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 商品展开和隐藏
	toggleProduct = (index, currentHeight, openHeight) => {
		let { listData } = this.state;
		listData[index].showItem = !listData[index].showItem;
		Animated.spring(currentHeight, {
			duration: 300,
			toValue: listData[index].showItem ? openHeight * scale : 138 * scale,
		}).start();
		this.setState({ listData })
	}

	_renderListItem = (data) => {
		let itemData = data.item;
		let { companyName, signTime, orderId, payExpireDays, totalAmount, totalQuantity, bizStaffName, bizTeamName,
			organName, tradeType, orderItemList, longOrderId } = itemData;
		let { currency } = orderItemList[0] || {}
		let { listData } = this.state;
		let unit = CURRENCY.getUnit(currency).text;
		let unitSymbol = CURRENCY.getUnit(currency).label;
		return (
			<View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, marginBottom: 12 * scale }}>
				<View style={[{ paddingBottom: 5 * scale }, data.index == listData.length - 1 ? { paddingBottom: 12 * scale } : '']}>
					<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
						<View style={{ flexDirection: 'row', flex: 1 }}>
							<Text numberOfLines={1} style={styles.cardTitle}>{companyName && companyName.length > 16 ? `${signTime.substring(0, 16)}...` : (companyName || '-')}</Text>
						</View>
						<Text style={styles.cardTitle}>双签日 {signTime && signTime.substring(0, 10)}</Text>
					</View>
					<View style={styles.listItem} >
						<TouchableOpacity activeOpacity={.6} onPress={() => { navigationSeevice.navigate('OrderDetailsPage', { orderId }) }}>
							<View style={styles.itemHeader}>
								<View style={{ flexDirection: 'row', alignItems: 'center' }}>
									<Text style={{ color: '#272727', fontSize: 13 * scale }}>{orderId || '-'}</Text>
									<Image source={tradeType == 'I' ? OrderCommon.iconData.innerImg : OrderCommon.iconData.outerImg} style={styles.orderTypeImg} />
									{longOrderId ? <Image source={OrderCommon.iconData.executeImg} style={styles.orderTypeImg} /> : null}
								</View>
								<Text style={[{ color: '#FA4516', fontSize: 13 * scale }]}>{`${payExpireDays || 0}天内付款`}</Text>
							</View>
							<View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * scale }}>
								<Text style={{ color: '#272727', fontSize: 12 * scale, opacity: .6 }}>{`业务员：${bizStaffName || '-'}（${bizTeamName || '-'} | ${organName || '-'}）`}</Text>
							</View>
							<Animated.View style={[styles.itemBody, orderItemList.length > 2 ? { height: itemData.boxHeight, overflow: 'hidden' } : '']}>
								{
									orderItemList && orderItemList.length && orderItemList.map((item, index) => {
										return (
											<View key={index}>
												<View style={styles.productItem}>
													{this._renderOrderProductItem(item, currency)}
												</View>
											</View>
										)
									})
								}
							</Animated.View>
						</TouchableOpacity>
						<View style={styles.itemFooter}>
							<Text style={{ fontSize: 13 * scale, color: '#272727' }}>共：{(totalQuantity || 0).toFixed(3)}吨， </Text>
							<View style={{ flexDirection: 'row', alignItems: 'center' }}>
								<Text style={{ fontSize: 13 * scale, color: '#272727' }}>合计：{unitSymbol}{MethodUtil.toThousands(totalAmount || 0, 2) || '-'}{unit}</Text>
							</View>
						</View>
					</View>
					{
						orderItemList && orderItemList.length > 2 ? (
							<TouchableOpacity activeOpacity={1} style={styles.toggleImg} onPress={() => this.toggleProduct(data.index, itemData.boxHeight, itemData.openHeight)}>
								<Image source={itemData.showItem ? closeImg : showImg} />
							</TouchableOpacity>
						) : null
					}
				</View>
			</View >
		)
	}

	_renderOrderProductItem = (item, currency) => {
		let { goodsName, price, quantity } = item;
		let unit = CURRENCY.getUnit(currency).text;
		let unitSymbol = CURRENCY.getUnit(currency).label;
		return (
			<View>
				<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: '50%' }}>
					<Text style={{ flex: 1, textAlign: 'left', fontWeight: 'bold', fontSize: 14 * scale }} numberOfLines={1}>{goodsName || '-'}</Text>
					<Text style={[{ flex: 1, textAlign: 'right' }]} numberOfLines={1}>
						<Text style={{ fontSize: 11 * scale }}>{unitSymbol}</Text>
						<Text style={{ fontSize: 14 * scale }}>{MethodUtil.toThousands(price || 0, 2) || '-'}</Text>
						<Text style={{ fontSize: 14 * scale }}>{unit}/吨</Text>
					</Text>
				</View>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', height: '50%' }}>
					<Text style={{ fontSize: 14 * scale, opacity: .6 }}> {(quantity || 0).toFixed(3) || '-'}吨</Text>
				</View>
			</View>
		)
	}

	render() {
		let { status, listData, refreshIcon, errorText } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.headerWrap}>
					<Text style={styles.headerWrapText}>(*销售订单“款到、保证金”，未完成全部预收款预警)</Text>
				</View>
				{/* 列表 */}
				{
					status == 'data' ?
						<View style={{ flex: 1, paddingBottom: 20 * scale, paddingTop: 16 * scale }}>
							<FlatList
								data={listData}
								style={styles.listWrap}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>
						: <PageStatusIndex status={status} errorText={errorText || '请求出错'} emptyText={'暂无记录'} onErrorPress={this.onErrorRefresh} />
				}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingBottom: 10 * scale
	},
	headerWrapText: {
		fontSize: 12 * scale,
		color: "#fff",
		textAlign: 'center',
		paddingBottom: 6 * scale
	},
	listWrap: {
		flex: 1,
	},
	orderTypeImg: {
		marginLeft: 5 * scale,
		height: 16 * scale,
		width: 16 * scale
	},
	listItem: {
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		marginTop: 7 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingBottom: 12 * scale,
		paddingTop: 12 * scale,
	},
	itemHeader: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	costTableRed: {
		borderRadius: 2 * scale,
		paddingHorizontal: 4 * scale,
		paddingVertical: 2 * scale,
		marginLeft: 5 * scale,
		backgroundColor: '#E02020'
	},
	itemBody: {
		position: 'relative',
		overflow: 'hidden',
		backgroundColor: '#fff',
		borderTopWidth: 1 / PixelRatio.get(),
		borderTopColor: '#EFEFEF',
		borderStyle: 'solid',
		marginTop: 12 * scale,
	},
	productItem: {
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		height: 68 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderBottomColor: '#EFEFEF',
		borderStyle: 'solid',
	},
	itemFooter: {
		height: 20 * scale,
		flexDirection: 'row',
		justifyContent: 'flex-end',
		alignItems: 'center',
		marginTop: 10 * scale
	},
	toggleImg: {
		height: 30 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
		marginBottom: 15 * scale,
	},
	cardTitle: {
		fontSize: 13 * scale,
		color: '#272727',
		opacity: .6
	}
})